import numpy as np
import pandas as pd

from classifier.maintaining_border import run_single_simulation, get_label_from_history


def run_multiple_simulations(params_df, time, n_simulations=50, window=100):
    """
    对每个参数组合运行多次模拟，获取稳态时种群均值
    :param params_df: generate_parameters生成的参数DataFrame
    :param time: 单次模拟时间
    :param n_simulations: 每个参数组合的模拟次数
    :param window: 稳态窗口长度
    :return: 包含稳态均值的DataFrame
    """
    results = []

    for idx, param_row in params_df.iterrows():
        # 存储每次模拟的均值
        lf_means, lc_means, hf_means, hc_means = [], [], [], []

        for _ in range(n_simulations):
            history = run_single_simulation(param_row, time)
            print(str(_)+"history生成成功")
            if history is not None and len(history['time']) > window:
                # 检查是否所有种群均达到稳态
                label = get_label_from_history(history, window=window)
                print(str(_)+"label生成成功")
                if label is not None:
                    # 计算窗口期均值
                    lf_means.append(np.mean(history['LF'][-window:]))
                    lc_means.append(np.mean(history['LC'][-window:]))
                    hf_means.append(np.mean(history['HF'][-window:]))
                    hc_means.append(np.mean(history['HC'][-window:]))

        # 计算平均结果（忽略NaN）
        result = {
            **param_row.to_dict(),
            'avg_LF': np.nanmean(lf_means),
            'avg_LC': np.nanmean(lc_means),
            'avg_HF': np.nanmean(hf_means),
            'avg_HC': np.nanmean(hc_means)
        }
        results.append(result)

    return pd.DataFrame(results)
